package com.tre.jdevtemplateboot.common.util;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program: jdev-boot-core
 * @description
 * @author: JDev
 * @create: 2021-07-30 08:27
 **/
@Slf4j
public class MD5Utils {

    private static final String SALT = "1a2b3c4d";
    private static final String[] DIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private MD5Utils(){}

    public static String inputPassToFormPass(String inputPass) {
        return encrypt32(""+SALT.charAt(0)+SALT.charAt(2)+inputPass+SALT.charAt(5)+SALT.charAt(4));
    }

    public static String formPassToDbPass(String formPass) {
        return encrypt32(""+SALT.charAt(0)+SALT.charAt(2)+formPass+SALT.charAt(5)+SALT.charAt(4));
    }

    public static String inputPassToDbPass(String input) {
        return formPassToDbPass(inputPassToFormPass(input));
    }

    private static String encrypt32(String strObj) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5Utils -> encrypt32 ->{}",e.getMessage());
            return "";
        }
        return byteToString(md.digest(strObj.getBytes()));
    }

    private static String byteToString(byte[] bByte) {
       StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bByte.length; i++) {
            builder.append(byteToArrayString(bByte[i]));
        }
        return builder.toString();
    }

    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return DIGITS[iD1] + DIGITS[iD2];
    }

}
